﻿#region Using Directives

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

#endregion

namespace GeekRule.ORM.Entities
{
    /// <summary>
    /// Base, abstract entity class for strongly-typed entities
    /// </summary>
    public abstract class EntityBase : IEntity
    {
        private EntityState _entityState = EntityState.NotSet;
        private Dictionary<string,object> _unmappedFields = new Dictionary<string, object>();

        /// <summary>
        /// Indicates the state of the entity
        /// </summary>
        public EntityState EntityState
        {
            get { return _entityState; }
            set { _entityState = value; }
        }

        /// <summary>
        /// Stores values in a data result set not found on the entity.
        /// DataMapping behavior must be set to StoreMissingFields for this to be populated.
        /// </summary>
        public Dictionary<string, object> UnmappedFields
        {
            get { return _unmappedFields; }
        }

        /// <summary>
        /// Overridden to provide list of all entity fields and their values
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            PropertyInfo[] properties = this.GetType().GetProperties();
            for (int i = 0; i < properties.Length; i++)
            {
                if (!properties[i].Name.Equals("UnmappedFields"))
                {
                    sb.AppendFormat("{0}:{1}{2}", properties[i].Name, properties[i].GetValue(this, null), Environment.NewLine);
                }
                else
                {
                    Dictionary<string, object> h = properties[i].GetValue(this, null) as Dictionary<string, object>;
                    if (h != null)
                    {
                        foreach (string key in h.Keys)
                        {
                            sb.AppendFormat("[Unmapped] {0}:{1}{2}", key, h[key].ToString(), Environment.NewLine);
                        }
                    }
                }
            }

            return sb.ToString();
        }
    }
}
